package org.j4me.info;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

import org.j4me.ui.Dialog;
import org.j4me.ui.UIManager;
import org.j4me.ui.components.HorizontalRule;
import org.j4me.ui.components.Label;
import org.j4me.ui.components.ProgressBar;
import org.j4me.util.Operation;
import org.j4me.util.OperationsQueue;

public class InfoScreen extends Dialog {
	private MIDlet _app;
	private DeviceInfo _deviceInfo;
	private ProgressBar _waiting;


	public InfoScreen(MIDlet app, DeviceInfo info) {
		
		_app = app;
		_deviceInfo = info;
		setTitle("J4ME - Device Info");
		setMenuText(null, null);
	}
	
	protected synchronized void paint(Graphics g) {
		
		super.paint(g);
		if(_waiting != null && _waiting.isShown())
		{
			int[] dimensions = _waiting.getPreferredSize( UIManager.getTheme(), getWidth(), getHeight() );
			_waiting.paint(g, UIManager.getTheme(), this, (getWidth()-dimensions[1])/2, (getHeight()-dimensions[1])/2, dimensions[1], dimensions[1], false);
		}
	}
	
	
	void showProgress(boolean show)
	{
		if(_waiting == null && show)
		{
			_waiting = new ProgressBar();
			_waiting.setMaxValue(0);
			_waiting.show(true);
			
		}
		else if(_waiting != null)
			_waiting.show(show);
		
		repaint();
	
	}
	
	boolean isWaiting()
	{
		return _waiting != null && _waiting.isShown();
	}

	public void populate() {
		
		OperationsQueue.push(new Operation() {

			
			public void execute() {
				
				try {
					
			
					append(new Label("Collecting basic infos ..."));
					repaint();
					_deviceInfo.collect();
					append(new Label("Collecting extended infos ..."));
					repaint();
					_deviceInfo.collectMoreInfo();
					append(new Label("Walk on keyboard, could be long ..."));
					ProgressBar bar = new ProgressBar();
					append(bar);
					repaint();
					
					_deviceInfo.collectCanvasInfo(bar);
					setSpacing(1);
					deleteAll();
					append(new Label("Press publish if you wish to collaborate to J4ME device database (no personal data were collected)"));
					append(new HorizontalRule());
					for(int i = 0; i < _deviceInfo.getCount();i++)
						append(new Label(_deviceInfo.getKey(i) + "=" + _deviceInfo.getStringValue(i) +""));
					setSelected(0);
					
				} catch (Throwable e) {
					append(new Label("Fatal error [" + e.getMessage() + "]"));
					append(new Label(e.getClass().getName()));
					setMenuText("Quit","");
					return;
				} finally {
					setMenuText(null, "Publish");
					repaint();
				}
				
			}});
		
		
	}
	
	protected void declineNotify() {
		_app.notifyDestroyed();
	}
	
	protected void acceptNotify() {
		if(OperationsQueue.getPendingOperations().size() != 0)
			return;
		
		OperationsQueue.push(new Operation() {

			public void execute() {
			
				showProgress(true);
				int code = -1;
				HttpConnection con = null;
				DataOutputStream out = null;
				try {
					code = -2;
					//con = (HttpConnection) Connector.open("http://localhost:8080/J4meDeviceInfo/collect");
					con = (HttpConnection) Connector.open("http://j4me.crickee.net/collect");
					code = -3;
					con.setRequestMethod("POST");			
					code= -4;
					out = con.openDataOutputStream();
					code= -5;
					out.writeInt(_deviceInfo.getCount());
					for (int i = 0; i < _deviceInfo.getCount(); i++) {
						code= -6;
						String key= _deviceInfo.getKey(i);
						String value = _deviceInfo.getStringValue(i);
						out.writeUTF(key);
						out.writeUTF(value);
					}
					code = -7;
					out.flush();
					
					code = con.getResponseCode();
	    			if (code != 200)
						throw new Exception("no access");
					
					 ExitScreen screen = new ExitScreen(_app,"Data have been send to server\nThanks very much for your help in building the J4ME Device Database !");
					 screen.show();
					
				} catch (SecurityException e) {
					 ExitScreen screen = new ExitScreen(_app,"Your help his needed !\n Please re run this Java app and  authorize internet access");
					 screen.show();
				} catch (Throwable e) {
					 MessageScreen screen = new MessageScreen(InfoScreen.this,"Cannot send data to J4ME's server [code=" + code +"] , check connection availability then retry \n" + e.getMessage() + " - " + e.getClass().getName());
					 screen.show();
					
						
				} finally {
					showProgress(false);
					if(out != null )
						try {
							out.close();
						} catch (IOException e) {

						}
					if(con != null)
						try {
							con.close();
						} catch (IOException e) {
						
						}
				}				
//				showProgress(true);
//				int code = 0;
//				int len = 0;
//				HttpConnection con = null;
//				DataOutputStream out = null;
//				try {
//					ByteArrayOutputStream bout = new ByteArrayOutputStream();
//					for (int i = 0; i < _deviceInfo.getCount(); i++) {
//						String key= _deviceInfo.getKey(i);
//						String value = _deviceInfo.getStringValue(i);
//						bout.write((char) key.length());
//						bout.write(key.getBytes());
//						bout.write((char) value.length());
//						bout.write(value.getBytes());
//						bout.flush();
//					}
//					bout.close();
//					byte[] all = bout.toByteArray();
//					len = all.length;
//					//con = (HttpConnection) Connector.open("http://localhost:8080/J4meDeviceInfo/collect");
//					con = (HttpConnection) Connector.open("http://tomcat.preprod.crickee.net/J4meDeviceInfo/collect");
//					con.setRequestMethod("POST");
//					con.setRequestProperty("Content-Length", "" + len);
//
//					out = con.openDataOutputStream();
//					out.
//					out.write(all);
//					out.flush();
//					code = con.getResponseCode();
//	    			if (code != 200)
//						throw new Exception("no access");
//					
//					 ExitScreen screen = new ExitScreen(_app,"Data have been send to server\nThanks very much for your help in building the J4ME Device Database !");
//					 screen.show();
//					
//				} catch (SecurityException e) {
//					 ExitScreen screen = new ExitScreen(_app,"Your help his needed !\n Please re run this Java app and  authorize internet access");
//					 screen.show();
//				} catch (Throwable e) {
//					 MessageScreen screen = new MessageScreen(InfoScreen.this,"Cannot send data to J4ME's server [sent="+ len + ",code=" + code +"] , check connection availability then retry");
//					 screen.show();
//					
//						
//				} finally {
//					showProgress(false);
//					if(out != null )
//						try {
//							out.close();
//						} catch (IOException e) {
//
//						}
//					if(con != null)
//						try {
//							con.close();
//						} catch (IOException e) {
//						
//						}
//				}
					
				
				
			}});
	}
}
